﻿#region zh-CHS 2006 - 2007 DemoSoft 团队 | en 2006 - 2007 DemoSoft Team

//     NOTES
// ---------------
//
// This file is a part of the G.O.S.E(Game Online Server Engine) for .NET.
//
//                 2006-2007 DemoSoft Team
//
//
// First Version : by H.Q.Cai - mailto:caihuanqing@hotmail.com

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published
 *   by the Free Software Foundation; either version 2.1 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

#region zh-CHS 包含名字空间 | en Include namespace
using System;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Demo_G.O.S.E.ServerEngine.Util;
using Demo_G.O.S.E.ServerEngine.World;
using Demo_G.O.S.E.ServerEngine.Common;
using Demo_G.O.S.E.ServerEngine.Network.DLL;
#endregion

namespace Demo_G.O.S.E.ServerEngine.Network
{
    /// <summary>
    /// 连接过来的客户端
    /// </summary>
    [MultiThreadedSupportgAttribute( "当前的类所有成员都可锁定,支持多线程操作" )]
    public class ClientSocketHandler : ACEClientHandlerAtServer
    {
        #region zh-CHS 构造和初始化和清理 | en Constructors and Initializers and Dispose
        /// <summary>
        /// 初始化构造
        /// </summary>
        public ClientSocketHandler()
        {
            this.EventThreadProcessMessageBlock += new EventDelegateClientHandlerProcessMessageBlock( this.OnProcessMessageBlock );
            this.EventThreadDisconnect += new EventDelegateClientHandlerDisconnect( this.OnDisconnect );
        }
        #endregion

        #region zh-CHS 共有属性 | en Public Properties
        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 接受到的数据包
        /// </summary>
        private ReceiveQueue m_Buffer = new ReceiveQueue();
        #endregion
        /// <summary>
        /// 接受到的数据存放处
        /// </summary>
        public ReceiveQueue Buffer
        {
            get { return m_Buffer; }
        }

        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 调用次数的累计数
        /// </summary>
        private long m_iAdding = 0;
        #endregion
        /// <summary>
        /// 调用次数的累计数
        /// </summary>
        internal long Adding
        {
            get { return m_iAdding; }
        }
        #endregion

        #region zh-CHS 私有的事件处理函数 | en Private Event Handlers
        /// <summary>
        /// 接受到新的数据包
        /// </summary>
        /// <param name="RecvMessageBlock"></param>
        private void OnProcessMessageBlock( ACEMessageBlock RecvMessageBlock )
        {
            // 内部已经有锁定
            m_Buffer.Enqueue( RecvMessageBlock.ReadIntPtr(), 0, RecvMessageBlock.WriteLength );

            // 数据包接收到的次数
            Interlocked.Increment( ref m_iAdding );
        }

        /// <summary>
        /// 断开
        /// </summary>
        private void OnDisconnect()
        {
        }

        #region zh-CHS 内部成员变量 | en Internal Member Variables
        /// <summary>
        /// 
        /// </summary>
        internal Listener m_Listener = null;
        #endregion
        /// <summary>
        /// 内部断开(调用后此类不得再进行任何处理,因为已返回进内存池)
        /// </summary>
        [MultiThreadedWarningAttribute( "此处没有锁定用于内部调用的(无锁),不支持多线程操作:警告!" )]
        internal void InternalDisconnect()
        {
            m_iAdding = 0;

            if ( m_Listener != null )
            {
                // 需要保存一个引用的副本,防止多线程在置空时候之前,再次设置值的可能
                Listener l_Listener = m_Listener;
                m_Listener = null;

                m_Buffer.Clear();
                l_Listener.Free( this );
            }
        }
        #endregion
    }

    /// <summary>
    /// 服务端监听
    /// </summary>
    [MultiThreadedSupportgAttribute( "当前的类所有成员都可锁定,支持多线程操作" )]
    public class Listener : IDisposable
    {
        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 主监听处理
        /// </summary>
        private ACESocketMainServer m_SocketMainServer  = new ACESocketMainServer();
        /// <summary>
        /// 是否已经处理过断开
        /// </summary>
        private bool m_Disposed = false;
        /// <summary>
        /// 监听到的客户端
        /// </summary>
        private Queue<ClientSocketHandler> m_Accepted   = new Queue<ClientSocketHandler>();
        /// <summary>
        /// 监听到的客户端的锁
        /// </summary>
        private object m_LockAccepted                   = new object();
        #endregion

        #region zh-CHS 构造和初始化和清理 | en Constructors and Initializers and Dispose
        /// <summary>
        /// 初始化构造
        /// </summary>
        public Listener()
        {
            m_SocketMainServer.EventThreadAcceptor += new EventDelegateAcceptor( this.OnAcceptor );
        }

        /// <summary>
        /// 断开
        /// </summary>
        public void Dispose()
        {
            if ( m_Disposed == false && m_SocketMainServer != null)
            {
                m_Disposed = true;

                try
                {
                    m_SocketMainServer.StopServer();
                }
                catch
                {
                    Debug.WriteLine( "Listener.Dispose(...) - m_SocketMainServer.StopServer(...) Exception error!" );
                }

                m_SocketMainServer = null;
            }
        }
        #endregion

        #region zh-CHS 共有属性 | en Public Properties
        /// <summary>
        /// 监听的主处理
        /// </summary>
        public ACESocketMainServer ListenerSocket
        {
            get { return m_SocketMainServer; }
        }

        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 管理当前的世界服务
        /// </summary>
        private BaseWorld m_BaseWorld = null;
        #endregion
        /// <summary>
        /// 管理当前的世界服务
        /// </summary>
        public BaseWorld BaseWorld
        {
            get { return m_BaseWorld; }
        }

        #region zh-CHS BaseWorld 方法 | en BaseWorld Method
        /// <summary>
        /// 设置管理当前的世界服务
        /// </summary>
        /// <param name="baseWorld"></param>
        internal void SetBaseWorld( BaseWorld baseWorld )
        {
            m_BaseWorld = baseWorld;
        }
        #endregion

        #endregion

        #region zh-CHS 共有方法 | en Public Methods
        /// <summary>
        /// 开始服务
        /// </summary>
        /// <param name="port">端口</param>
        /// <returns></returns>
        public bool StartServer( int port )
        {
            return m_SocketMainServer.StartServer( port );
        }

        /// <summary>
        /// 开始服务
        /// </summary>
        /// <param name="strHostNamePort">地址和端口</param>
        /// <returns></returns>
        public bool StartServer( string strHostNamePort )
        {
            return m_SocketMainServer.StartServer( strHostNamePort );
        }
        #endregion

        #region zh-CHS 内部方法 | en Internal Method
        #region zh-CHS 私有静态成员变量 | en Private Static Member Variables
        /// <summary>
        /// 空的ClientSocketHandler数组
        /// </summary>
        private static ClientSocketHandler[] s_EmptySockets = new ClientSocketHandler[0];
        #endregion
        /// <summary>
        /// 获取新的联接过来的客户端
        /// </summary>
        /// <returns></returns>
        internal ClientSocketHandler[] Slice()
        {
            ClientSocketHandler[] l_ArrayReturn = s_EmptySockets;

            Monitor.Enter( m_LockAccepted );
            do
            {
                if ( m_Accepted.Count <= 0 )
                    break;

                l_ArrayReturn = m_Accepted.ToArray();

                // 清空数据,让它的调用着来处理这些数据
                m_Accepted.Clear();
            } while ( false );
            Monitor.Exit( m_LockAccepted );

            return l_ArrayReturn;
        }

        /// <summary>
        /// 释放指定的客户端到内存池里面
        /// </summary>
        /// <param name="clientSocketHandler"></param>
        internal void Free( ClientSocketHandler clientSocketHandler )
        {
            // 返回至内存池
            clientSocketHandler.SocketHandlerManager.Value  = IntPtr.Zero;
            ACESocketHandlerManagerAtServer l_SocketHandlerManager = clientSocketHandler.SocketHandlerManager;
            clientSocketHandler.SocketHandlerManager = null;
            m_SocketHandlerManagerAtServerPool.ReleasePoolContent( l_SocketHandlerManager );

            // 返回至内存池
            clientSocketHandler.Value = IntPtr.Zero;
            m_ClientHandlerAtServerPool.ReleasePoolContent( clientSocketHandler );
        }
        #endregion

        #region zh-CHS 私有的事件处理函数 | en Private Event Handlers
        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 
        /// </summary>
        private ACEProcessMessageBlockPool<ClientSocketHandler> m_ClientHandlerAtServerPool = new ACEProcessMessageBlockPool<ClientSocketHandler>( "Listener - ClientSocketHandler", 1024 );
        /// <summary>
        /// 
        /// </summary>
        private ACEProcessMessageBlockPool<ACESocketHandlerManagerAtServer> m_SocketHandlerManagerAtServerPool = new ACEProcessMessageBlockPool<ACESocketHandlerManagerAtServer>( "Listener - ACESocketHandlerManagerAtServer", 1024 );
        #endregion
        /// <summary>
        /// 连接新的客户端的处理
        /// </summary>
        /// <param name="NonceClientHandler"></param>
        /// <param name="AllHandlerManager"></param>
        /// <param name="ClientHandlerAtServer"></param>
        private void OnAcceptor( ACEClientHandlerAtServer NonceClientHandler, ACESocketHandlerManagerAtServer AllHandlerManager, out ACEClientHandlerAtServer ClientHandlerAtServer )
        {
            ClientHandlerAtServer = null;

            SocketConnectEventArgs l_eventArgs = new SocketConnectEventArgs( NonceClientHandler );
            EventSink.InvokeSocketConnect( l_eventArgs );

            // 如果允许连接
            if ( l_eventArgs.AllowConnection )
            {
                ClientSocketHandler l_ClientHandler = m_ClientHandlerAtServerPool.AcquirePoolContent();
                if ( l_ClientHandler == null )
                {
                    Debug.WriteLine( "Listener.OnAcceptor(...) - l_ClientHandler == null error!" );

                    return;
                }
                l_ClientHandler.m_Listener = this;

                ACESocketHandlerManagerAtServer l_SocketHandlerManager = m_SocketHandlerManagerAtServerPool.AcquirePoolContent();
                if ( l_SocketHandlerManager == null )
                {
                    Debug.WriteLine( "Listener.OnAcceptor(...) - l_SocketHandlerManager == null error!" );

                    m_ClientHandlerAtServerPool.ReleasePoolContent( l_ClientHandler );

                    return;
                }

                l_ClientHandler.Value = NonceClientHandler.Value;
                l_ClientHandler.SocketHandlerManager = l_SocketHandlerManager;
                l_ClientHandler.SocketHandlerManager.Value = AllHandlerManager.Value;
                ClientHandlerAtServer = l_ClientHandler as ACEClientHandlerAtServer;

                Monitor.Enter( m_LockAccepted );
                {
                    m_Accepted.Enqueue( l_ClientHandler );
                }
                Monitor.Exit( m_LockAccepted );

                LOGs.WriteLine( LogMessageType.MSG_INFO, "新连接: {0}  [在线连接数 {1}] [总连接数 {2}]", NonceClientHandler.ClientAddress, AllHandlerManager.OnlineClientCount, AllHandlerManager.ClientCount );
                
                // 有新的连接过来需要发送全局信号处理新的连接
                if ( m_BaseWorld != null )
                    m_BaseWorld.SetWorldSignal();
                else
                    Debug.WriteLine( "Listener.OnAcceptor(...) - m_BaseWorld == null error!" );
            }
            else // 不允许连接
            {
                try
                {
                    NonceClientHandler.CloseSocket();
                }
                catch
                {
                    Debug.WriteLine( "Listener.OnAcceptor(...) - NonceClientHandler.CloseSocket(...) Exception error!" );
                }

                LOGs.WriteLine( LogMessageType.MSG_WARNING, "新连接: {0} 无法通过验证被断开! [在线连接数 {1}] [总连接数 {2}]", NonceClientHandler.ClientAddress, AllHandlerManager.OnlineClientCount, AllHandlerManager.ClientCount );
            }
        }
        #endregion
    }
}
#endregion

